<?php
/*
 * Created on 29.01.2006
 * 
 * config:
 * file         Filename of file to load.
 * defaultfile  Default file to load, if 'file' does not exists.
 */

m2import('phpinchains/Filter.php');

class LoadFileFilter extends phpinchains_Filter
{
    
    var $config;

    function doFilter (& $env, & $chain)
    {
        if (isset($this->config['cache-headers']) && $this->config['cache-headers']=='true') {
            header("Cache-Control: max-age=3600, must-revalidate");
            header("Expires: " . gmdate("D, d M Y H:i:s", time()+86400) . " GMT");
            header("Pragma: cache");
        }
        if (file_exists($this->config['file'])) {
            if (isset($this->config['contenttype-by-extension']) && $this->config['contenttype-by-extension']=='true') {
                header("Content-Type: ".$this->getType(file_get_contents($this->config['file'])));
            }
            print file_get_contents($this->config['file']);
        } else {
            if (isset($this->config['contenttype-by-extension']) && $this->config['contenttype-by-extension']=='true') {
                header("Content-Type: ".$this->getType(file_get_contents($this->config['file'])));
            }
            print file_get_contents($this->config['defaultfile']);
        }
        $chain->doFilter($env);
    }

    function getType ($file) {
        $type = 'application/octet-stream';
        preg_match('/\.(\w+)$/', $file, $matches);
        switch (strtolower($matches[1])) {
            case 'jpg':
                return 'image/jpeg';
                break;
            case 'gif':
                return 'image/gif';
                break;
            case 'js':
                return 'text/javascript';
                break;
            case 'css':
                return 'text/css';
                break;
            case 'png':
                return 'image/png';
                break;
            default:
                return 'application/octet-stream';
                break;
        }
    }
    
    function init (& $config)
    {
        $this->config = & $config;
        if (!$this->config['file'])
            print "LoadFileFilter: attribute 'file' ist required<br/>";
    }

}
?>